Page({
  data: {
    // 倒计时相关
    totalMinutes: 120,
    remainingSeconds: 120 * 60,
    formattedTime: '120:00',
    timer: null,
    
    // 题目相关
    questions: [
      {
        id: 1,
        type: '单选题',
        content: '下列哪个是JavaScript的基本数据类型？',
        options: ['Array', 'String', 'Object', 'Function'],
        isCollected: false,
        userAnswer: null
      },
      {
        id: 2,
        type: '多选题',
        content: '下列哪些属于前端框架？',
        options: ['React', 'Django', 'Vue', 'Flask'],
        isCollected: false,
        userAnswer: null
      },
      {
        id: 3,
        type: '判断题',
        content: '微信小程序只能使用JavaScript进行开发。',
        options: ['正确', '错误'],
        isCollected: false,
        userAnswer: null
      },
      {
        id: 4,
        type: '单选题',
        content: 'HTML中，哪个标签用于定义文档的主体？',
        options: ['<header>', '<body>', '<main>', '<section>'],
        isCollected: false,
        userAnswer: null
      },
      {
        id: 5,
        type: '单选题',
        content: 'CSS中，哪个属性用于改变元素的背景颜色？',
        options: ['color', 'text-color', 'background', 'background-color'],
        isCollected: false,
        userAnswer: null
      }
    ],
    currentQuestionIndex: 0,
    currentQuestion: null,
    selectedOption: null,
    questionsStatus: [],
    
    // 弹窗控制
    showAnswerCard: false,
    showDraftPaper: false,
    showSubmitConfirm: false,
    showCollectToast: false,
    
    // 草稿纸相关
    isDrawing: false,
    lastX: 0,
    lastY: 0,
    lineColor: '#000000',
    lineWidth: 3,
    canvasRect: null,
    
    // 交卷相关
    unansweredCount: 0
  },
  
  onLoad() {
    this.initQuestionsStatus();
    this.startTimer();
    this.setData({
      currentQuestion: this.data.questions[0]
    });
    this.setCurrentQuestionData();
  },
  
  onUnload() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },
  
  // 初始化题目状态
  initQuestionsStatus() {
    const status = this.data.questions.map(question => ({
      status: question.userAnswer !== null ? 'answered' : 'unanswered',
      isCollected: question.isCollected
    }));
    this.setData({ questionsStatus: status });
  },
  
  // 开始倒计时
  startTimer() {
    const timer = setInterval(() => {
      let seconds = this.data.remainingSeconds - 1;
      
      if (seconds < 0) {
        clearInterval(timer);
        this.calculateUnanswered();
        this.setData({ showSubmitConfirm: true });
        return;
      }
      
      const minutes = Math.floor(seconds / 60);
      const remainingSecs = seconds % 60;
      const formatted = `${minutes.toString().padStart(2, '0')}:${remainingSecs.toString().padStart(2, '0')}`;
      
      this.setData({
        remainingSeconds: seconds,
        formattedTime: formatted
      });
    }, 1000);
    
    this.setData({ timer });
  },
  
  // 设置当前题目数据
  setCurrentQuestionData() {
    const currentQuestion = this.data.questions[this.data.currentQuestionIndex];
    this.setData({
      selectedOption: currentQuestion.userAnswer !== null 
        ? currentQuestion.userAnswer 
        : (currentQuestion.type === '多选题' ? [] : null),
      isCollected: currentQuestion.isCollected
    });
  },
  
  // 判断选项是否被选中
  isOptionSelected: function(type, selectedOption, index) {
    if (type === '多选题') {
      return Array.isArray(selectedOption) && selectedOption.includes(index);
    } else {
      return selectedOption === index;
    }
  },
  
  // 选择答案
  selectOption(e) {
    const index = e.currentTarget.dataset.index;
    const questions = [...this.data.questions];
    const currentQuestion = questions[this.data.currentQuestionIndex];
    
    if (currentQuestion.type === '多选题') {
      // 初始化数组如果不存在
      if (!Array.isArray(currentQuestion.userAnswer)) {
        currentQuestion.userAnswer = [];
      }
      
      // 切换选项状态
      const optionIndex = currentQuestion.userAnswer.indexOf(index);
      if (optionIndex === -1) {
        currentQuestion.userAnswer.push(index);
        currentQuestion.userAnswer.sort((a, b) => a - b); // 保持顺序
      } else {
        currentQuestion.userAnswer.splice(optionIndex, 1);
      }
    } else {
      currentQuestion.userAnswer = index;
    }
    
    // 更新状态
    const questionsStatus = [...this.data.questionsStatus];
    questionsStatus[this.data.currentQuestionIndex].status = 
      currentQuestion.userAnswer !== null && 
      (currentQuestion.type !== '多选题' || currentQuestion.userAnswer.length > 0) 
        ? 'answered' 
        : 'unanswered';
    
    this.setData({
      questions,
      selectedOption: currentQuestion.userAnswer, // 确保更新
      questionsStatus
    });
  },
  
  // 上一题
  prevQuestion() {
    if (this.data.currentQuestionIndex > 0) {
      const newIndex = this.data.currentQuestionIndex - 1;
      this.setData({
        currentQuestionIndex: newIndex,
        currentQuestion: this.data.questions[newIndex]
      }, () => {
        this.setCurrentQuestionData();
      });
    }
  },
  
  // 下一题
  nextQuestion() {
    if (this.data.currentQuestionIndex < this.data.questions.length - 1) {
      const newIndex = this.data.currentQuestionIndex + 1;
      this.setData({
        currentQuestionIndex: newIndex,
        currentQuestion: this.data.questions[newIndex]
      }, () => {
        this.setCurrentQuestionData();
      });
    }
  },
  
  // 切换收藏状态
  toggleCollect() {
    const questions = [...this.data.questions];
    const isCollected = !questions[this.data.currentQuestionIndex].isCollected;
    questions[this.data.currentQuestionIndex].isCollected = isCollected;
    
    const questionsStatus = [...this.data.questionsStatus];
    questionsStatus[this.data.currentQuestionIndex].isCollected = isCollected;
    
    this.setData({
      questions,
      isCollected,
      questionsStatus,
      showCollectToast: true
    });
    
    setTimeout(() => {
      this.setData({ showCollectToast: false });
    }, 2000);
  },
  
  // 显示答题卡
  showAnswerCard() {
    this.setData({ showAnswerCard: true });
  },
  
  // 隐藏答题卡
  hideAnswerCard() {
    this.setData({ showAnswerCard: false });
  },
  
  // 跳转到指定题目
  jumpToQuestion(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentQuestionIndex: index,
      currentQuestion: this.data.questions[index],
      showAnswerCard: false
    }, () => {
      this.setCurrentQuestionData();
    });
  },
  
  // 显示草稿纸
  showDraftPaper() {
    this.setData({ showDraftPaper: true }, () => {
      const query = wx.createSelectorQuery().in(this);
      query.select('#draftCanvas')
        .fields({ node: true, size: true })
        .exec(res => {
          const canvas = res[0].node;
          this.canvas = canvas;
          this.ctx = canvas.getContext('2d');
          
          const dpr = wx.getSystemInfoSync().pixelRatio;
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          this.ctx.scale(dpr, dpr);
          
          this.ctx.lineCap = 'round';
          this.ctx.lineJoin = 'round';
          this.ctx.strokeStyle = this.data.lineColor;
          this.ctx.lineWidth = this.data.lineWidth;
          
          this.setData({
            canvasRect: {
              width: res[0].width,
              height: res[0].height
            }
          });
        });
    });
  },
  
  // 隐藏草稿纸
  hideDraftPaper() {
    this.setData({ showDraftPaper: false, isDrawing: false });
  },
  
  // 获取画布坐标
  getCanvasCoordinates: function(e) {
    const query = wx.createSelectorQuery().in(this);
    let x, y;
    
    if (e.touches && e.touches.length > 0) {
      query.select('#draftCanvas').boundingClientRect(rect => {
        x = e.touches[0].clientX - rect.left;
        y = e.touches[0].clientY - rect.top;
      }).exec();
    } else {
      query.select('#draftCanvas').boundingClientRect(rect => {
        x = e.clientX - rect.left;
        y = e.clientY - rect.top;
      }).exec();
    }
    
    return { x, y };
  },
  
  // 开始绘制
  startDrawing(e) {
    const { x, y } = this.getCanvasCoordinates(e);
    
    this.setData({
      isDrawing: true,
      lastX: x,
      lastY: y
    });
  },
  
  // 绘制中
  draw(e) {
    if (!this.data.isDrawing || !this.ctx) return;
    
    const { x, y } = this.getCanvasCoordinates(e);
    const { lastX, lastY } = this.data;
    
    this.ctx.beginPath();
    this.ctx.moveTo(lastX, lastY);
    this.ctx.lineTo(x, y);
    this.ctx.stroke();
    
    this.setData({ lastX: x, lastY: y });
  },
  
  // 结束绘制
  endDrawing() {
    this.setData({ isDrawing: false });
  },
  
  // 清除草稿
  clearDraft() {
    if (!this.canvas || !this.ctx) return;
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
  },
  
  // 显示交卷确认
  showSubmitConfirm() {
    this.calculateUnanswered();
    this.setData({ showSubmitConfirm: true });
  },
  
  // 隐藏交卷确认
  hideSubmitConfirm() {
    this.setData({ showSubmitConfirm: false });
  },
  
  // 计算未答题数量
  calculateUnanswered() {
    const count = this.data.questions.filter(q => q.userAnswer === null).length;
    this.setData({ unansweredCount: count });
  },
  
// 提交考试
submitExam() {
  // 计算考试结果数据
  const examResult = this.calculateExamResult();
  
  // 保存数据到本地存储
  wx.setStorageSync('latestExamResult', examResult);
  
  wx.showToast({
    title: '交卷成功',
    icon: 'success',
    duration: 1500, // 缩短提示时间
    mask: true, // 添加遮罩防止用户操作
    success: () => {
      setTimeout(() => {
        // 尝试跳转并添加错误处理
        wx.navigateTo({
          url: '/index/pages/examReport/examReport',
          success: () => {
            console.log('跳转成功');
          },
          fail: (err) => {
            console.error('跳转失败:', err);
            // 如果navigateTo失败，尝试用redirectTo
            wx.redirectTo({
              url: '/index/pages/examReport/examReport',
              fail: (err2) => {
                console.error('redirectTo也失败:', err2);
                // 显示错误提示
                wx.showToast({
                  title: '跳转失败，请重试',
                  icon: 'none'
                });
              }
            });
          }
        });
      }, 1500);
    }
  });
},
  
  // 计算考试结果
  calculateExamResult() {
    const questionPoints = this.data.questions.map(q => {
      switch(q.type) {
        case '单选题': return 2;
        case '多选题': return 4;
        case '判断题': return 1;
        default: return 2;
      }
    });
    
    const correctAnswers = [1, [0, 2], 1, 1, 3];
    
    let totalScore = 0;
    let correctCount = 0;
    const wrongQuestionsList = [];
    const questionTypeStats = {
      '单选题': { correct: 0, total: 0 },
      '多选题': { correct: 0, total: 0 },
      '判断题': { correct: 0, total: 0 }
    };
    
    this.data.questions.forEach((question, index) => {
      questionTypeStats[question.type].total++;
      
      let isCorrect = false;
      if (question.type === '多选题') {
        isCorrect = JSON.stringify(question.userAnswer) === JSON.stringify(correctAnswers[index]);
      } else {
        isCorrect = question.userAnswer === correctAnswers[index];
      }
      
      if (isCorrect) {
        totalScore += questionPoints[index];
        correctCount++;
        questionTypeStats[question.type].correct++;
      } else if (question.userAnswer !== null) {
        wrongQuestionsList.push({
          number: index + 1,
          content: question.content,
          yourAnswer: this.getAnswerText(question, question.userAnswer),
          correctAnswer: this.getAnswerText(question, correctAnswers[index])
        });
      }
    });
    
    const maxScore = questionPoints.reduce((sum, points) => sum + points, 0);
    const scorePercentage = Math.round((totalScore / maxScore) * 100);
    
    let grade, assessment;
    if (scorePercentage >= 90) {
      grade = "优秀";
      assessment = "恭喜你取得了优异成绩！";
    } else if (scorePercentage >= 75) {
      grade = "良好";
      assessment = "表现不错，继续努力！";
    } else if (scorePercentage >= 60) {
      grade = "及格";
      assessment = "基本掌握，但仍需巩固。";
    } else {
      grade = "不及格";
      assessment = "需要加强学习，再接再厉！";
    }
    
    const totalSeconds = this.data.totalMinutes * 60;
    const usedSeconds = totalSeconds - this.data.remainingSeconds;
    const minutesUsed = Math.floor(usedSeconds / 60);
    const secondsUsed = usedSeconds % 60;
    const timeSpent = `${minutesUsed}分钟${secondsUsed > 0 ? secondsUsed + '秒' : ''}`;
    
    return {
      score: totalScore,
      maxScore: maxScore,
      scorePercentage: scorePercentage,
      grade: grade,
      assessment: assessment,
      examName: "前端知识测试",
      examTime: new Date().toLocaleString(),
      timeSpent: timeSpent,
      
      totalQuestions: this.data.questions.length,
      correctAnswers: correctCount,
      wrongAnswers: this.data.questions.length - correctCount - this.data.unansweredCount,
      unansweredCount: this.data.unansweredCount,
      accuracy: Math.round((correctCount / this.data.questions.length) * 100),
      
      questionTypes: [
        { 
          type: "单选题", 
          correct: questionTypeStats['单选题'].correct, 
          total: questionTypeStats['单选题'].total, 
          rate: `${Math.round((questionTypeStats['单选题'].correct / questionTypeStats['单选题'].total) * 100)}%`
        },
        { 
          type: "多选题", 
          correct: questionTypeStats['多选题'].correct, 
          total: questionTypeStats['多选题'].total, 
          rate: `${Math.round((questionTypeStats['多选题'].correct / questionTypeStats['多选题'].total) * 100)}%`
        },
        { 
          type: "判断题", 
          correct: questionTypeStats['判断题'].correct, 
          total: questionTypeStats['判断题'].total, 
          rate: `${Math.round((questionTypeStats['判断题'].correct / questionTypeStats['判断题'].total) * 100)}%`
        }
      ],
      
      wrongQuestionsList: wrongQuestionsList
    };
  },

  // 辅助方法：将答案索引转换为选项文本
  getAnswerText(question, answerIndex) {
    if (!answerIndex && answerIndex !== 0) return "未答题";
    
    if (question.type === '多选题') {
      return answerIndex.map(index => {
        return `${String.fromCharCode(65 + index)}. ${question.options[index]}`;
      }).join('; ');
    } else {
      return `${String.fromCharCode(65 + answerIndex)}. ${question.options[answerIndex]}`;
    }
  }
});